/*TODO Refactor because DO NOT WORK*/

package ru.osu.acm.system.sourcediff;

import java.util.*;

public class SourceReformation {



    
	public SourceReformation() {

	}

	TreeMap<String, String> dictionary = new TreeMap<String, String>();

	public String reform(String src) {
		dictionary.clear();
		char srcArr[] = src.toCharArray();
		String cur = "";
		int ident = 0;
		int i = 0;
		boolean funcName = true;
		String ret = "";
		while (true) {
			if (i >= srcArr.length)
				break;
			if ((srcArr[i] >= 'a' && srcArr[i] <= 'z')
					|| (srcArr[i] >= 'A' && srcArr[i] <= 'Z')
					|| (srcArr[i] >= '0' && srcArr[i] <= '9')) {
				cur += srcArr[i];
			} else {
				if (srcArr[i] == '=' || srcArr[i] == ',')
					funcName = false;
				else if(srcArr[i]==';'||srcArr[i]=='}')
					funcName = true;
				int cnt = 0;
				if (srcArr[i] == ';' || srcArr[i] == ',' || srcArr[i] == ')'
						|| srcArr[i] == '{' || srcArr[i] == '='
						|| srcArr[i] == '(') {
					if (srcArr[i] == '(') {
						if (funcName && !dictionary.containsKey(cur)
								&& ident == 1 && cur.length() > 0
								&& (cur.charAt(0) > '9' || cur.charAt(0) < '0')) {
							dictionary.put(cur, "");
						} else
							;
					} else if (!dictionary.containsKey(cur) && ident == 1
							&& cur.length() > 0
							&& (cur.charAt(0) > '9' || cur.charAt(0) < '0')) {
						dictionary.put(cur, "");
					}
					if (srcArr[i] == ',')
						ident = 1;
					else
						ident = 0;
				} else if (srcArr[i] == ']' || srcArr[i] == '>'  || srcArr[i]=='*') {
					ident = 1;
				} else if (srcArr[i] == '\\') {
					i++;
					cnt++;
				} else if (srcArr[i] == '\'') {
					i++;
					cnt++;
					while (srcArr[i] != '\'' && i < srcArr.length) {
						i++;
						cnt++;
					}
				} else if (srcArr[i] == '\"') {
					i++;
					cnt++;
					while (srcArr[i] != '\"' && i < srcArr.length) {
						i++;
						cnt++;
					}
				} else if (srcArr[i] == '<' && i+1<srcArr.length && srcArr[i]!='<') {
					int oldi = i;
					int oldcnt = cnt;
					i++;
					cnt++;
					while (srcArr[i] != '>' && i < srcArr.length) {
						if (srcArr[i] == ';') {
							i = oldi;
							cnt = oldcnt;
							break;
						}
						i++;
						cnt++;
					}
				} else if (srcArr[i] == ' ') {
					ident = 1;
				}
				if (!dictionary.containsKey(cur))
					ret += cur;
				cnt++;
				for (int y = cnt - 1; y >= 0; y--) {
					ret += srcArr[i - y];
				}
				cur = "";
			}
			i++;
		}
		return ret;
	}
}
